########################################################################
#  Searx-Qt - Lightweight desktop application for Searx.
#  Copyright (C) 2020-2022  CYBERDEViL
#
#  This file is part of Searx-Qt.
#
#  Searx-Qt is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  Searx-Qt is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
########################################################################


import urllib.parse


class NetworkTypes:
    """ Custom definitions for network types, the ones from stats2 don't
    include I2P.
    """
    Web = 0
    Tor = 1
    I2P = 2

    def netTypeFromUrl(url):
        """Returns the network type as a int based on the given
        url it's extension.
        """
        parsedUrl = urllib.parse.urlparse(url)
        extSplit = parsedUrl.hostname.split('.')
        ext = extSplit[(len(extSplit)-1)]
        if ext == 'onion':
            return NetworkTypes.Tor
        elif ext == 'i2p':
            return NetworkTypes.I2P
        else:
            return NetworkTypes.Web


class HandlerProto:
    def __init__(self, requestsHandler):
        """ Prototype for handling/updating instances and engines data.

        @param requestsHandler: Handler for doing requests
        @type requestsHandler: searxqt.core.requests.RequestsHandler
        """
        self.requestsHandler = requestsHandler
        self._instances = {}
        self._engines = {}
        self._lastUpdated = 0

    def lastUpdated(self): return self._lastUpdated

    @property
    def instances(self): return self._instances

    @property
    def engines(self): return self._engines

    def data(self):
        return {
            'instances': self._instances,
            'engines': self._engines,
            'lastUpdate': self._lastUpdated
        }

    def setData(self, data):
        """
        @param data: json object (instances.json)
        @type data: dict/json
        """
        self.clear()
        self._instances.update(data.get('instances', {}))
        self._engines.update(data.get('engines', {}))
        self._lastUpdated = data.get('lastUpdate', 0)

    def clear(self):
        self._instances.clear()
        self._engines.clear()
